package com.mathlearning.auth.service;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.dto.ChangePasswordRequest;
import com.mathlearning.auth.dto.UpdateUserProfileRequest;
import com.mathlearning.auth.dto.UploadResponse;
import com.mathlearning.auth.dto.UserInfo;
import com.mathlearning.auth.dto.user.UserStatsResponse;
import com.mathlearning.auth.entity.User;
import com.mathlearning.auth.entity.UserStats;
import com.mathlearning.auth.repository.DiscussionRepository;
import com.mathlearning.auth.repository.FollowRepository;
import com.mathlearning.auth.repository.UserRepository;
import com.mathlearning.auth.repository.UserStatsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserStatsRepository userStatsRepository;

    @Autowired
    private OSSService ossService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Autowired
    private DiscussionRepository discussionRepository;
    
    @Autowired
    private FollowRepository followRepository;

    /**
     * 获取用户资料
     */
    public UserInfo getUserProfile(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        return new UserInfo(user);
    }

    /**
     * 更新用户资料
     */
    @Transactional
    public UserInfo updateUserProfile(Long userId, UpdateUserProfileRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        // 更新昵称
        if (request.getNickname() != null && !request.getNickname().isEmpty()) {
            user.setNickname(request.getNickname());
        }

        // 更新性别
        if (request.getGender() != null) {
            if (request.getGender() < 0 || request.getGender() > 2) {
                throw new BusinessException("性别值无效");
            }
            user.setGender(request.getGender());
        }

        // 更新生日
        if (request.getBirthday() != null && !request.getBirthday().isEmpty()) {
            try {
                LocalDate birthday = LocalDate.parse(request.getBirthday(), DateTimeFormatter.ISO_DATE);
                user.setBirthday(birthday);
            } catch (Exception e) {
                throw new BusinessException("生日格式不正确，请使用 YYYY-MM-DD 格式");
            }
        }

        // 更新个人介绍
        if (request.getBio() != null) {
            user.setBio(request.getBio());
        }

        // 更新学校
        if (request.getSchool() != null) {
            user.setSchool(request.getSchool());
        }

        // 更新年级
        if (request.getGrade() != null) {
            user.setGrade(request.getGrade());
        }

        // 保存
        user = userRepository.save(user);

        logger.info("用户资料更新成功 - 用户ID: {}", userId);

        return new UserInfo(user);
    }

    /**
     * 上传头像
     */
    @Transactional
    public UploadResponse uploadAvatar(Long userId, MultipartFile file) {
        // 上传到 OSS
        String url = ossService.uploadAvatar(file, userId);

        // 更新用户表
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        user.setAvatar(url);
        userRepository.save(user);

        // 构建响应
        UploadResponse response = new UploadResponse();
        response.setUrl(url);
        response.setFilename(url.substring(url.lastIndexOf("/") + 1));
        response.setSize(file.getSize());
        response.setUploadTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        logger.info("头像上传成功 - 用户ID: {}, URL: {}", userId, url);

        return response;
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(Long userId, ChangePasswordRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        // 验证旧密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            throw new BusinessException("旧密码错误");
        }

        // 验证新密码格式
        if (request.getNewPassword().length() < 6 || request.getNewPassword().length() > 20) {
            throw new BusinessException("新密码长度必须在6-20个字符之间");
        }

        // 加密新密码
        String encodedPassword = passwordEncoder.encode(request.getNewPassword());
        user.setPassword(encodedPassword);
        
        userRepository.save(user);

        logger.info("密码修改成功 - 用户ID: {}", userId);
    }

    /**
     * 获取用户学习统计
     */
    public UserStats getUserStats(Long userId) {
        return userStatsRepository.findByUserId(userId).orElse(null);
    }
    
    /**
     * 获取用户卡片统计数据
     */
    public UserStatsResponse getUserStatsResponse(Long targetUserId, Long currentUserId) {
        // 查询目标用户
        User targetUser = userRepository.findById(targetUserId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        // 计算统计数据
        Long totalViews = discussionRepository.sumViewsByAuthorId(targetUserId);
        Long totalLikes = discussionRepository.sumLikesByAuthorId(targetUserId);
        Long totalFavorites = discussionRepository.sumFavoritesByAuthorId(targetUserId);
        Long followers = followRepository.countFollowers(targetUserId);
        
        // 检查当前用户是否已关注目标用户
        Boolean isFollowed = false;
        if (currentUserId != null && !currentUserId.equals(targetUserId)) {
            isFollowed = followRepository.existsByFollowerIdAndFollowingId(currentUserId, targetUserId);
        }
        
        // 构建响应
        UserStatsResponse response = new UserStatsResponse();
        response.setId(targetUser.getId());
        response.setNickname(targetUser.getNickname());
        response.setUsername(targetUser.getPhone());  // 使用手机号作为username
        response.setAvatar(targetUser.getAvatar());
        response.setLocation(targetUser.getSchool());  // 使用学校作为location，或者可以添加新字段
        response.setTotalViews(totalViews != null ? totalViews : 0L);
        response.setTotalLikes(totalLikes != null ? totalLikes : 0L);
        response.setTotalFavorites(totalFavorites != null ? totalFavorites : 0L);
        response.setFollowers(followers);
        response.setIsFollowed(isFollowed);
        response.setIsVerified(false);  // 默认未认证，后续可扩展
        
        return response;
    }
}

